# -*- coding: utf-8 -*-
import requests
import time
from pb.comfuc import Comfuc
from pb.sport import Sport
import logging
from datetime import datetime

def get_current_datetime():
    now = datetime.now()
    return now.strftime('%Y-%m-%d %H:%M:%S')

class GetPBodds:
    v = 0
    session = requests.Session()
    last_login_time_stamp = 0
    last_sports = []
    headers = {
        "Host": "www.pin135.com",
        "Sec-Ch-Ua-Platform": "Windows",
        "Sec-Ch-Ua": 'Chromium";v="134", "Not:A-Brand";v="24", "Google Chrome";v="134"',
        "Sec-Ch-Ua-Mobile": "?0",
        "X-Trust-Client": "false",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36",
        "Accept": "application/json, text/plain, */*",
        "Origin": "https://www.pin135.com",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer": "https://www.pin135.com",
        "Priority": "u=1, i"
    }

    def login(self):
        """
        sesion 一个小时过期一次，所以我们在58分钟的时候应该出现登录一下账户
        :return:
        """
        url = "https://www.pin135.com/member-service/v2/authenticate"
        params = {
            "locale": "zh_CN",
            "_": str(int(time.time() * 1000)),
            "withCredentials": "true"
        }
        data = {
            "captcha": "",
            "captchaToken": "",
            "loginId": "pangchaojie",
            "password": "plj3ytovvt25"
        }
        response = self.session.post(url, params=params, headers=self.headers, data=data)
        if response.text =='0':
            print(f'登录失败{response.text}')
        jdata = response.json().get('tokens')
        self.headers['X-Lcu'] = jdata.get('X-Lcu')
        self.headers['X-U'] = jdata.get('X-U')
        self.headers['X-Slid'] = jdata.get('X-SLID')
        self.headers['X-Custid'] = jdata.get('X-Custid')
        self.headers['X-Browser-Session-Id'] = jdata.get('X-Browser-Session-Id')
        self.v = 0
        print(f"login---{get_current_datetime()} and tokens={jdata}")
        self.last_login_time_stamp = time.time()
        #print(self.headers)



    def fetch_match_list(self):
        # 设置 SOCKS5 代理
#https://www.rowilong.com/sports-service/sv/compact/events?btg=1&c=&cl=3&d=&ec=&ev=&g=QQ%3D%3D&hle=false&ic=false&inl=false&l=3&lang=&lg=&lv=&me=0&mk=1&more=false&o=1&ot=1&pa=0&pimo=0%2C1%2C8%2C39%2C2%2C3%2C6%2C7%2C4%2C5&pn=-1&pv=1&sp=29&tm=0&v=1740071613588&locale=zh_CN&_=1740071676977&withCredentials=true
        # URL 和用户名、密码 locale=zh_C 改成 en_US
        t = int(time.time() * 1000)
        url = 'https://www.pin135.com/sports-service/sv/compact/events?btg=1&c=&cl=3&d=&ec=&ev=&g=QQ%3D%3D&hle=false&ic=false&inl=false&l=3&lang=&lg=&lv=&me=1606456973&mk=1&more=false&o=1&ot=1&pa=0&pimo=0%2C1%2C8%2C39%2C2%2C3%2C6%2C7%2C4%2C5&pn=-1&pv=1&sp=29&tm=0&v='+str(self.v)+'&locale=en_US&_=' + str(
            t) + '&withCredentials=true'

        try:


            response = self.session.get(url, headers=self.headers, timeout=10)

            if response.status_code == 200:
                #cookies = self.session.cookies
                jdata = response.json()
                if jdata['u']:
                    self.v = jdata['u'][0][2]
                elif jdata['l']:
                    self.v = jdata['l'][0][3]
                return response.json()
            else:
                logging.error(f"请求失败，状态码：{response.status_code}")
                logging.error("响应内容：", response.text)

        except Exception as e:
            logging.error(f"请求过程中发生错误：{e}")
            time.sleep(6)


    def getList(self):
        if time.time() - self.last_login_time_stamp >3500:
            self.login()
            self.last_login_time_stamp = time.time()
            time.sleep(5)
        sports = []
        list = self.fetch_match_list()
        if is_string_empty(list['n']):
            return self.last_sports
        for ls in list['n'][0][2]:
            lsname = ls[1]
            for bs in ls[2]:
                sport = Sport(bs[1], bs[2], lsname)
                sport.sport_id = bs[0]
                sport.start_time = bs[4]
                if bs[8].get('0')[11] ==2:
                    #print(f'{sport.match}  锁盘')
                    continue
                #锁盘的时候下面2个函数为空
                if bs[8].get('0') is None:
                    continue
                for odd_ou in bs[8].get('0')[1]:
                    if is_string_empty(odd_ou[2]) or is_string_empty(odd_ou[3]):
                        continue
                    sport.full_ou_odd[odd_ou[1]] = [float(odd_ou[2]), float(odd_ou[3])]
                for odd_hdp in bs[8].get('0')[0]:
                    if is_string_empty(odd_hdp[3]) or is_string_empty(odd_hdp[4]):
                        continue
                    sport.full_hdp_odd[odd_hdp[1]] = [float(odd_hdp[3]), float(odd_hdp[4])]
                if len(sport.full_hdp_odd) == 0:
                    continue
                odds = next(iter(sport.full_hdp_odd.values()))
                return_rate = Comfuc.calculate_return_rate(odds[0], odds[1])
                if sport.start_time / 1000 - time.time() < 3600 and return_rate > 96:
                    sport.return_rate = return_rate
                    sports.append(sport)
        self.last_sports = sports
        return sports

def is_string_empty(s):
    """
    检查字符串是否为 None 或空字符串。

    参数:
    s (str): 要检查的字符串。

    返回:
    bool: 如果字符串为 None 或空字符串，返回 True，否则返回 False。
    """
    if s is None:
        return True
    if isinstance(s, str) and s == '':
        return True
    return False

if __name__ == "__main__":
    getPBodds = GetPBodds()
    time.sleep(5)
    while True:
        sports = getPBodds.getList()
        if len(sports)>0:
            print(f'{sports[0].match}  OU  = {sports[0].full_ou_odd}')
        time.sleep(15)

